package com.anji.sp.aspect;

import com.anji.sp.exception.DemoModeException;
import com.anji.sp.model.LoginUser;
import com.anji.sp.service.impl.TokenServiceImpl;
import com.anji.sp.util.SecurityUtils;
import com.anji.sp.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * Created by raodeming on 2020/6/29.
 */
@Aspect
@Component
@Slf4j
public class ControllerRequestAspect {

    /**
     * 定义切点
     */
    @Pointcut("execution(* com.anji.sp.controller..*(..))")
    public void requestServer() {
    }


    /**
     * guest 用户为在线体验用户，权限校验
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("requestServer()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.nonNull(loginUser) && loginUser.getUser().getUsername().equals(TokenServiceImpl.USER_LOGIN_USERNAME)) {
            String url = ServletUtils.getRequest().getRequestURI();
            log.info("url :{}", url);
            if (url.contains("/insert") | url.contains("/save") | url.contains("/delete") | url.contains("/update") | url.contains("/uploadFile") | url.contains("/enable")) {
                log.info("演示用户,权限不足 url: {}, {}, {}", url, loginUser.getUser().getName(), loginUser.getUser().getUserId());
                throw new DemoModeException();
            }
        }
        //执行方法
        return point.proceed();
    }
}
